import { ConflictException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcrypt';
import { plainToClass } from 'class-transformer';
import { UpdateUserDto } from './dto/update-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async hashPassword(
    password: string,
    saltOrRounds: number = 10,
  ): Promise<string> {
    return await bcrypt.hash(password, saltOrRounds);
  }

  async create(createUserDto: CreateUserDto) {
    try {
      const user = await this.userRepository.findOneBy({
        name: createUserDto.name,
      });

      if (user) {
        throw new ConflictException(
          `用户名 << ${createUserDto.name} >> 已经被注册了，请使用其他用户名注册`,
        );
      }

      const result = await this.userRepository.create({
        ...createUserDto,
        nickname: createUserDto.name,
        password: await this.hashPassword(createUserDto.password),
      });
      return this.userRepository.save(result);
    } catch (error) {
      if (error.code === 'ERR_DUP_ENTRY') {
        throw new ConflictException('id already exist');
      }
      throw error;
    }
  }

  findAll() {
    const userList = this.userRepository.find();
    return plainToClass(User, userList);
  }
  findOne(name: string) {
    return this.userRepository.findOneBy({ name });
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    delete updateUserDto.password;
    return this.userRepository.update(id, updateUserDto);
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }

  async removeList(ids: number[]) {
    return await this.userRepository
      .createQueryBuilder()
      .delete()
      .from(User)
      .whereInIds(ids)
      .execute();
  }

  clear() {
    return this.userRepository.clear();
  }
}
